//定义js命名空间
Ext.namespace('FsCarInfo.FsCarInventory');
//TODO : 完善数据结构
//DateTime -- date , decimal -- float
// { name: 'Department.Name', mapping: 'Department.Name' },
// { name: 'Department'},
//FsCarInventory FieldArray
FsCarInfo.FsCarInventory.BaseFieldsArray = new Array(
	{ name: 'Id', type: 'string' },
	{ name: 'Type', type: 'string' },
	{ name: 'InveDate', type: 'date' },
	{ name: 'DeptId', type: 'string' },
	{ name: 'Department.Name', mapping: 'Department.Name' },
	{ name: 'ReviUserId', type: 'string' },
	//{ name: 'ReviUser', mapping: 'ReviUser.Name' },
	{ name: 'State', type: 'int' },
	{ name: 'IsDelete', type: 'bool' },
	{ name: 'Version', type: 'int' },
	{ name: 'Createuser', type: 'string' },
	{ name: 'Createtime', type: 'date' }
);

//FsCarInventory JsonReader
FsCarInfo.FsCarInventory.JsonReader = Ext.extend(Infrastructure.BaseJsonReader, {
	constructor: function (cfg) {
		cfg = cfg || {};
		FsCarInfo.FsCarInventory.JsonReader.superclass.constructor.call(this, Ext.apply({
			fields: FsCarInfo.FsCarInventory.BaseFieldsArray
		}, cfg));
	}
});

//FsCarInventory JsonStore
FsCarInfo.FsCarInventory.JsonStore = Ext.extend(Infrastructure.BaseJsonStore, {
	constructor: function (cfg) {
		cfg = cfg || {};
		FsCarInfo.FsCarInventory.JsonStore.superclass.constructor.call(this, Ext.apply({
			url: '/FsCarInventory/GetPlist',
			params: {
				start: 0,
				limit: ALL_PAGESIZE_SETTING
			},
			remoteSort: true,
			fields: FsCarInfo.FsCarInventory.BaseFieldsArray,
			listeners: {
				'remove': function (thiz, record, index) {
					Ext.Ajax.request({
						url: '/FsCarInventory/Delete?Id=' + record.data.Id,
						success: function (response, opts) {
							var result = Ext.util.JSON.decode(response.responseText);
							if (result.success == false) {
								JsHelper.ShowError(result.msg);
								this.insert(0, record);
							}
						}
					});
				}
			}
		}, cfg));
	}
});

//FsCarInventory GridPanel Ext.grid.GridPanel
FsCarInfo.FsCarInventory.GridPanel = Ext.extend(Infrastructure.BaseGridPanel, {
	// User property
	//基本处理Url
	baseUrl: '/FsCarInventory/',
	//提交保存Url
	formSubmitUrl: '/FsCarInventory/SaveOrUpdate',
	//提交保存提示信息
	formSubmitMsg: '确定要保存吗?',
	//工具栏标签
	tbarMask: '0',
	//表格列默认显示
	columnMask: '1',
	//状态
	itemState: '',

	// Property
	stripeRows: true,
	frame: true,
	border: true,
	layout: 'fit',
	loadMask: true,
	enableColumnMove: false,
	viewConfig: {
		autoFill: true
	},
	store: new FsCarInfo.FsCarInventory.JsonStore(),
	stateful: true,
	stateId: 'FsCarInfo.FsCarInventory.GridPanel',

	//constructor
	initComponent: function () {
		//prepare

		var itemGrid = this;
		var tbarMask = this.tbarMask;
		var colMask = this.columnMask;
		var cmdAddEntity = this.onAddEntity;
		var cmdDeleteEntity = this.onDeleteEntity;
		var cmdLoadEntity = this.onLoadEntity;
		var cmdQueryList = this.onQueryList;
		var cmdClearFilter = this.onClearFilter;
		//提交审批
		var cmdTbarCmd = function () {
			this.tbarSubmit(this.baseUrl + 'MethodName', '确定要提交吗?', '您的信息提交到系统..');
		};
		//set store params
		this.store.setBaseParam('state', this.itemState);

		// The filter.
		var filters = new Ext.ux.grid.GridFilters({
			encode: true,
			filters: [
				{ dataIndex: 'Type', type: 'list', options: FsCarInfo.Params.InventoryTypeStore.reader.arrayData },
				{ dataIndex: 'InveDate', type: 'date' },
				{ dataIndex: 'Department.Name', type: 'list', options: JsHelper.GetFilterListData(Infrastructure.DeptStore.data.items, 'Name', 'Name') },
				{ dataIndex: 'ReviUserId', type: 'string' },
				{ dataIndex: 'State', type: 'list', options: FsCarInfo.Params.InventoryStateStore.reader.arrayData },
				{ dataIndex: 'Createuser', type: 'string' },
				{ dataIndex: 'Createtime', type: 'string' }
			]
		});

		// selModel
		var selModel = new Ext.grid.CheckboxSelectionModel({
			//header: '',
			//singleSelect: true,
			menuDisabled: true,
			listeners: {
				'selectionchange': function (sm) {
					// 控制工具栏按钮是否可用
					//itemGrid.saveButton.setDisabled(sm.getCount() < 1);
				}
			}
		});

		// columnModel 对于不常需要显示的 hidden: true 
		var gridColumn = new Ext.grid.ColumnModel({
			columns: [
				new Ext.grid.RowNumberer(),
				selModel,
				{ header: "盘点类型", dataIndex: 'Type', hidden: this.columnMask.charAt(1) == '0',
					renderer: function (v) {
						return v == "" ? "v" : FsCarInfo.Params.InventoryTypeStore.getById(v).get('Name');
					}
				},
				{ header: "盘点日期", dataIndex: 'InveDate', xtype: 'datecolumn', format: 'Y年m月d日 H:i', hidden: this.columnMask.charAt(1) == '0' },
				{ header: "盘点机构", dataIndex: 'Department.Name', hidden: this.columnMask.charAt(1) == '0' },
				{ header: "复核用户ID", dataIndex: 'ReviUser.Name', hidden: this.columnMask.charAt(1) == '0' },
				{ header: "状态", dataIndex: 'State', hidden: this.columnMask.charAt(1) == '0',
					renderer: function (v) {
						return v == null ? "未知" : FsCarInfo.Params.InventoryStateStore.getById(v).get('Name');
					}
				}
			],
			defaults: {
				sortable: true,
				menuDisabled: false
			}
		});

		// PageBar
		var pagebBar = new Infrastructure.BasePagingToolbar({
			store: this.store,
			plugins: this.plugins
		});

		// 常用工具栏
		var toolBar = new Ext.Toolbar({
			items: [{
				xtype: 'tbaraddbtn',
				hidden: tbarMask.substring(0, 1) != '1',
				handler: cmdAddEntity,
				scope: itemGrid
			}, {
				hidden: tbarMask.substring(0, 1) != '1',
				xtype: 'tbseparator'
			}, {
				xtype: 'tbardelbtn',
				hidden: tbarMask.substring(0, 1) != '1',
				handler: cmdDeleteEntity,
				scope: itemGrid
			}, '-', {
				xtype: 'tbarresetbtn',
				handler: cmdClearFilter,
				scope: itemGrid
			}, '-']
		});

		Ext.apply(this, {
			plugins: [filters],
			sm: selModel,
			cm: gridColumn,
			tbar: new Ext.Toolbar({
				items: [{
					xtype: 'tbaraddbtn',
					hidden: tbarMask.substring(0, 1) != '1',
					handler: cmdAddEntity,
					scope: itemGrid
				}, {
					hidden: tbarMask.substring(0, 1) != '1',
					xtype: 'tbseparator'
				}, {
					xtype: "tbbutton",
					ref: '../delBtn',
					minWidth: 80,
					//disabled: true,
					text: "删除",
					cls: "x-btn-text-icon",
					icon: "/Content/icons/delete.png",
					hidden: tbarMask.substring(0, 1) != '1',
					handler: cmdDeleteEntity,
					scope: itemGrid
				}]
			}),
			bbar: pagebBar,
			listeners: {
				'rowdblclick': cmdLoadEntity
			}
		});

		FsCarInfo.FsCarInventory.GridPanel.superclass.initComponent.call(this);
	},

	/****************** 
	* user function 
	******************/

	// 添加
	onAddEntity: function () {
		var itemGrid = this;
		var itemEditForm = new FsCarInfo.FsCarInventory.EditForm({
			listeners: {
				'afterSave': function (ele, rt) {
					if (rt) {
						ele.form.reset();
						var itemGridStore = itemGrid.store;
						itemGridStore.reload();
						JsHelper.ShowInfo('添加信息成功!');
					}
				}
			}
		});
		var itemEditWin = new FsCarInfo.FsCarInventory.EditWin({
			items: [itemEditForm]
		});
		itemEditWin.show();
	},

	// 读取信息显示
	onLoadEntity: function () {
		var itemGrid = this;
		var selRecord = this.getSelectionModel().getSelected();
		if (selRecord == null) {
			JsHelper.ShowError('请选择记录..');
			return -1;
		}
		var selId = selRecord.data.Id;
		var inveListGrid = new FsCarInfo.FsCarInventoryList.GridPanel({
			height: 500,
			inventoryId: selId
		});
		var itemEditWin = new Ext.Window({
			title: 'FsCarInventoryList Infomation',
			iconCls: 'application_form',
			width: 800,
			autoHeight: true,
			resizable: false,
			constrain: true,
			modal: true,
			closeAction: 'close',
			plain: true,
			buttonAlign: 'center',
			items: [inveListGrid]
		});
		itemEditWin.show();
		inveListGrid.store.load({
			params: {
				start: 0,
				limit: ALL_PAGESIZE_SETTING
			}
		});
	},

	// 删除
	onDeleteEntity: function () {
		var itemGrid = this;
		var itemGridStore = this.store;
		JsHelper.DelConfirm(function (btn) {
			if (btn == 'yes') {
				var s = itemGrid.getSelectionModel().getSelections();
				for (var i = 0, r; r = s[i]; i++) {
					itemGridStore.remove(r);
				}
			}
		});
	},

	// 查询
	onQueryList: function () {
		var itemGrid = this;
		var q_query = Ext.getCmp('q_query').getValue();
		itemGrid.store.load({
			params: {
				start: 0,
				limit: ALL_PAGESIZE_SETTING,
				q_query: q_query
			}
		})
	},

	// 清空筛选数据
	onClearFilter: function () {
		var itemGrid = this;
		itemGrid.filters.clearFilters();
	},

	// 提交选定记录..
	tbarSubmit: function (submitUrl, confirmMsg, successMsg) {
		var itemGrid = this;
		var selRecord = this.getSelectionModel().getSelected();
		if (selRecord == null) {
			JsHelper.ShowError('未选择记录.');
			return -1;
		}
		var selId = selRecord.data.Id;
		JsHelper.Confirm(confirmMsg, function (btn) {
			if (btn == 'yes') {
				var ids = [];
				var s = itemGrid.getSelectionModel().getSelections();
				for (var i = 0, r; r = s[i]; i++) {
					ids.push(r.data.Id);
				}
				//加载进度条
				Ext.MessageBox.show({
					msg: '正在提交数据到中心服务器...',
					progressText: '保存数据...',
					width: 300,
					wait: true,
					waitConfig: { interval: 1000 }
				});
				Ext.Ajax.request({
					url: submitUrl,
					params: {
						'Ids': ids.toString()
					},
					success: function (response, opts) {
						Ext.MessageBox.hide();
						var result = Ext.util.JSON.decode(response.responseText);
						if (result.success == false) {
							JsHelper.ShowError('操作失败:' + result.msg);
						} else {
							itemGrid.store.reload();
							Ext.Msg.alert('提示,操作成功', '成功。' + successMsg);
						}
					},
					failure: function (form, action) {
						Ext.MessageBox.hide();
						JsHelper.ShowError('系统异常:' + action.result.msg);
					}
				});
			}
		});
	}
});

//FsCarInventory EditForm
FsCarInfo.FsCarInventory.EditForm = Ext.extend(Infrastructure.BaseForm, {
	Id: null,
	dataRecord: null,
	submitUrl: '/FsCarInventory/CreateNewInventory',
	submitMsg: '确定要保存吗?',

	initComponent: function () {
		var itemEditForm = this;
		var cmdUpdate = this.onSave;

		//Form第一列
		// 定义表单列
		var firstColumn = [{
			fieldLabel: "盘点类型",
			name: 'Type',
			hiddenName: 'Type',
			width: 150,
			xtype: 'combo',
			triggerAction: 'all',
			mode: 'local',
			store: FsCarInfo.Params.InventoryTypeStore,
			valueField: 'Code',
			displayField: 'Name'
		}, {
			fieldLabel: "盘点机构",
			width: 150,
			maxLength: 36,
			xtype: 'deptcombo',
			hiddenName: 'DeptId'
		}];

		Ext.apply(this, {
			items: [firstColumn],
			buttons: [{
				xtype: 'btnsubmit',
				handler: cmdUpdate,
				hidden: this.submitUrl == '',
				scope: itemEditForm
			}, {
				xtype: 'btncancle',
				handler: function () {
					itemEditForm.ownerCt.destroy();
				}
			}],
			reader: new FsCarInfo.FsCarInventory.JsonReader()
		});

		FsCarInfo.FsCarInventory.EditForm.superclass.initComponent.call(this);

		//定义保存后执行的事件
		this.addEvents('afterSave');
	},

	/****************** 
	* user function 
	******************/

	//更新保存信息
	onSave: function () {
		var itemForm = this;
		var id = this.Id;
		var saveUrl = this.submitUrl;
		if (itemForm.getForm().isValid()) {
			JsHelper.Confirm(this.submitMsg, function (btn) {
				if (btn != 'no') {
					itemForm.getForm().submit({
						waitMsg: '正在提交....',
						url: saveUrl,
						params: {
							'Id': (id == null) ? '' : id
						},
						success: function (form, action) {
							//返回结果后触发保存事件
							itemForm.fireEvent('afterSave', itemForm, true);
						},
						failure: function (form, action) {
							JsHelper.ShowError(action.result.msg);
						}
					});
				}
			});
		}
	}
});

//FsCarInventory DetailWin
FsCarInfo.FsCarInventory.EditWin = Ext.extend(Ext.Window, {
	title: '添加库存盘点',
	iconCls: 'application_form',
	width: 300,
	resizable: false,
	constrain: true,
	autoHeight: true,
	modal: true,
	closeAction: 'close',
	plain: true,
	buttonAlign: 'center',

	//constructor
	initComponent: function () {
		FsCarInfo.FsCarInventory.EditWin.superclass.initComponent.call(this);
	}
});
